package com.grq.mis.service;


import cn.hutool.core.lang.Validator;
import com.grq.mis.component.UploadComponent;
import com.grq.mis.dao.DepartmentDao;
import com.grq.mis.dao.UserDao;
import com.grq.mis.entity.Department;
import com.grq.mis.exception.BusinessException;
import com.grq.mis.exception.ResultEnum;
import com.grq.mis.model.sys.Me;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Transactional
@Service
public class DepartmentService extends BaseService<Department>{

    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UploadComponent uploadComponent;

    public void addDepartment(Department department, Me me, MultipartFile img) {

        if (img != null && Validator.isNotEmpty(img.getOriginalFilename())){
            String url = uploadComponent.uploadImg(img);
            department.setLogo(url);
        }


        department.setIsDisable(false);
        department.setCreateTime(new Date());
        department.setCreateUserId(me.getId());
        departmentDao.insert(department);

    }

    public void updateDepartment(Department model, MultipartFile img) {

        Department department = departmentDao.single(model.getId());
        if (department == null){
            throw new BusinessException(ResultEnum.DEPARTMENT_IS_NULL);
        }

        if (img != null && Validator.isNotEmpty(img.getOriginalFilename())){
            String url = uploadComponent.uploadImg(img);
            department.setLogo(url);
        }

        department.setName(model.getName());
        department.setDescription(model.getDescription());
        department.setIsDisable(model.getIsDisable());
        departmentDao.updateById(department);

    }

    public void deleteDepartment(Long id) {

        Department department = departmentDao.single(id);
        if (department == null){
            throw new BusinessException(ResultEnum.DEPARTMENT_IS_NULL);
        }

        departmentDao.deleteById(id);
        userDao.deleteDepartmentId(id);

    }
    
}
